package com.humanminoritygame.validator;

import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.humanminoritygame.form.UserRegistrationForm;
import com.humanminoritygame.model.UserRepo;

public class UserRegistrationValidator implements Validator {
  private static final Pattern EMAIL_PATTERN = Pattern.compile("^\\w+([_\\.-]\\w+)*@(\\w+([_\\.-]\\w+)*)");
  UserRepo userRepo;

  public UserRegistrationValidator(UserRepo userRepo){
    this.userRepo = userRepo;
  }

  @Override
  public boolean supports(Class<?> aClass) {
    return UserRegistrationForm.class.isAssignableFrom(aClass);
  }

  @Override
  public void validate(Object obj, Errors errors) {
    UserRegistrationForm userRF = (UserRegistrationForm)obj;

    if(userRF.getUser()==null || userRF.getUser().equals("")){
      errors.rejectValue("name", "Invalid Name");
    }

    if(userRF.getPass1()==null || userRF.getPass1().equals("")){
      errors.rejectValue("pass1", "Invalid Password");
    }

    if(userRF.getPass2()==null || userRF.getPass2().equals("")){
      errors.rejectValue("pass2", "Invalid Password");
    }

    if(!userRF.getPass1().equals(userRF.getPass2())){
      errors.rejectValue("pass2", "Password Mismatch");
    }

    validateEmail(userRF.getEmail(), errors);

    if(userRepo.getUserByName(userRF.getUser()) != null) {
      errors.rejectValue("user", "Invalid Name. Please choose another one");
    }
  }

  private void validateEmail(String email, Errors errors) {
    if(email == null || email.equals("")){
      errors.rejectValue("email", "Invalid Email");
    }
    if (!EMAIL_PATTERN.matcher(email).matches())
    {
        errors.rejectValue("email", "Invalid Email pattern") ;
    }
  }
}
